<?php

namespace app\forms\field;

use yii\db\Exception;
use app\models\Field;
use yii\web\HttpException;
use app\helpers\ArrayHelper;
use app\validators\PositiveInteger;

/**
 * 字段 编辑
 */
class UpdateForm extends BaseForm
{
    public $id;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['id', PositiveInteger::class],
            ['id', 'required'],
            ['id', 'exist', 'targetClass' => Field::class]
        ]);
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            $model = Field::findOne($form['id']);
            $attr = ArrayHelper::humpToUnderline($form->getAttributes());
            unset($attr['id']);
            $model->setAttributes($attr);
            $model->save(false);
        } catch (Exception $e) {
            $form->serverError();
        }

        $form->updateOk();
    }
}